using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using Common;
using Common.Enum;
using Controls;
using Converters;
using Microsoft.Win32;
using SProject;
using SProject.Program;
using SSettings;

namespace ProjectView.Windows
{
	public partial class ProjectManageWindow : UserControl, IComponentConnector, IStyleConnector
	{
		public delegate void DelegateOnProjectEvent(object sender, ProjectRoutedEventArgs e);

		public static readonly RoutedEvent OnProjectIsUsingRoutedEvent = EventManager.RegisterRoutedEvent("OnProjectIsUsingRoutedEvent", RoutingStrategy.Bubble, typeof(EventHandler<ProjectRoutedEventArgs>), typeof(ProjectManageWindow));

		private Project _CopiedProject;

		private CollectionViewSource view = new CollectionViewSource();

		public Project CopiedProject
		{
			get
			{
				return _CopiedProject;
			}
			set
			{
				_CopiedProject = value;
				OnPropertyChanged("CopiedProject");
			}
		}

		public event RoutedEventHandler OnProjectIsUsing
		{
			add
			{
				AddHandler(OnProjectIsUsingRoutedEvent, value);
			}
			remove
			{
				RemoveHandler(OnProjectIsUsingRoutedEvent, value);
			}
		}

		public event DelegateOnProjectEvent OnProjectEdit;

		[field: NonSerialized]
		public event PropertyChangedEventHandler PropertyChanged;

		public bool Close()
		{
			for (int num = TabControl.Items.Count - 1; num > 0; num--)
			{
				ProjectModifyMainWindow projectModifyMainWindow = ((TabItem)TabControl.Items[num]).Content as ProjectModifyMainWindow;
				if (projectModifyMainWindow != null && !projectModifyMainWindow.Close())
				{
					return false;
				}
			}
			return true;
		}

		private void win_OnProjectEdit(object sender, ProjectRoutedEventArgs e)
		{
			if (e.Project == null)
			{
				return;
			}
			for (int i = 1; i < TabControl.Items.Count; i++)
			{
				TabItem tabItem = (TabItem)TabControl.Items[i];
				ProjectModifyMainWindow projectModifyMainWindow = tabItem.Content as ProjectModifyMainWindow;
				if (projectModifyMainWindow != null && projectModifyMainWindow.Project == e.Project)
				{
					TabControl.SelectedItem = tabItem;
					return;
				}
			}
			CreateNewTabItem(e.Project);
		}

		private void CreateNewTabItem(Project project)
		{
			foreach (TabItem item in (IEnumerable)TabControl.Items)
			{
				if (item is TabItemCloseable && item.Content is ProjectModifyMainWindow && ((ProjectModifyMainWindow)item.Content).Project.BasicInfo.Name == project.BasicInfo.Name)
				{
					item.IsSelected = true;
					return;
				}
			}
			ProjectRoutedEventArgs projectRoutedEventArgs = new ProjectRoutedEventArgs();
			projectRoutedEventArgs.RoutedEvent = OnProjectIsUsingRoutedEvent;
			projectRoutedEventArgs.Project = project;
			projectRoutedEventArgs.IsUsing = false;
			ProjectRoutedEventArgs projectRoutedEventArgs2 = projectRoutedEventArgs;
			RaiseEvent(projectRoutedEventArgs2);
			if (projectRoutedEventArgs2.IsUsing)
			{
				MessageBox.Show(string.Format(Utility.GetMessage("msg_project_edit_deny"), project.BasicInfo.Name, projectRoutedEventArgs2.ExperimentName), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
				return;
			}
			project.IsEditing = true;
			ProjectModifyMainWindow projectModifyMainWindow = new ProjectModifyMainWindow(project);
			projectModifyMainWindow.OnProjectSave += projectWindow_OnProjectSave;
			projectModifyMainWindow.OnProjectClose += projectWindow_OnProjectClose;
			TabItemCloseable tabItemCloseable = new TabItemCloseable();
			tabItemCloseable.Style = Utility.GetResource("TabItemCloseableStyleDefault") as Style;
			tabItemCloseable.CloseTab += item_CloseTab;
			tabItemCloseable.IsSelected = true;
			tabItemCloseable.Content = projectModifyMainWindow;
			Binding binding = new Binding();
			binding.Path = new PropertyPath("Name");
			binding.Source = projectModifyMainWindow.ModifyProject.BasicInfo;
			binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
			binding.Mode = BindingMode.OneWay;
			binding.Converter = new StringUnderlineConverter();
			tabItemCloseable.SetBinding(HeaderedContentControl.HeaderProperty, binding);
			TabControl.Items.Add(tabItemCloseable);
		}

		private void item_CloseTab(object sender, RoutedEventArgs e)
		{
			ProjectModifyMainWindow projectModifyMainWindow = ((TabItemCloseable)sender).Content as ProjectModifyMainWindow;
			if (projectModifyMainWindow != null)
			{
				projectModifyMainWindow.Close();
			}
			e.Handled = true;
		}

		private void projectWindow_OnProjectClose(object sender, EventArgs e)
		{
			ProjectModifyMainWindow projectModifyMainWindow = sender as ProjectModifyMainWindow;
			if (projectModifyMainWindow != null)
			{
				projectModifyMainWindow.Project.IsEditing = false;
				TabControl.Items.Remove(projectModifyMainWindow.Parent);
			}
		}

		private void projectWindow_OnProjectSave(object sender, EventArgs e)
		{
			if (TabControl.Items.Count > 1 && ((TabItem)TabControl.Items[1]).Content is ProjectManageWindow)
			{
				((ProjectManageWindow)((TabItem)TabControl.Items[1]).Content).RefreshProjectList(false);
			}
			if (sender is ProjectModifyMainWindow)
			{
				ConfigSettings.GetInstance().History.AddProjectHistory(((ProjectModifyMainWindow)sender).Project.GetFilePath());
			}
		}

		private void OpenProject(string name)
		{
			Project project = ProjectManage.GetInstance().GetProject(Path.GetFileNameWithoutExtension(name));
			if (project != null)
			{
				CreateNewTabItem(project);
			}
			else if (MessageBox.Show(Utility.GetMessage("msg_project_notexist"), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
			{
				ConfigSettings.GetInstance().History.RemoveProjectHistory(name);
			}
		}

		public void OnPropertyChanged(string propertyName)
		{
			if (string.IsNullOrEmpty(propertyName))
			{
				throw new ArgumentException("propName");
			}
			if (this.PropertyChanged != null)
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		public ProjectManageWindow()
		{
			base.Initialized += ProjectManageWindow_Initialized;
			InitializeComponent();
			gridProjectNameList.Loaded += gridProjectNameList_Loaded;
		}

		private void ProjectManageWindow_Initialized(object sender, EventArgs e)
		{
			comboAllProjectType.ItemsSource = EnumManagement.GetAllDisplayProjectType();
			view.Source = ProjectManage.GetInstance().AllProjectList;
			view.Filter += view_Filter;
			view.View.SortDescriptions.Add(new SortDescription("BasicInfo.Name", ListSortDirection.Ascending));
			gridProjectNameList.ItemsSource = view.View;
			ProjectManage.GetInstance().AllProjectList.CollectionChanged += AllProjectList_CollectionChanged;
			comboAllProjectType.SelectedIndex = 0;
			OnProjectEdit += win_OnProjectEdit;
			RefreshProjectList();
		}

		private void AllProjectList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			view.View.Refresh();
		}

		private void gridProjectNameList_Loaded(object sender, RoutedEventArgs e)
		{
			gridProjectNameList.Focus();
		}

		private void view_Filter(object sender, FilterEventArgs e)
		{
			bool accepted = false;
			Project project = e.Item as Project;
			KeyValuePair keyValuePair = comboAllProjectType.SelectedItem as KeyValuePair;
			if (project != null && keyValuePair != null)
			{
				if ((EProjectType)keyValuePair.Key == EProjectType.All)
				{
					accepted = true;
				}
				else if ((EProjectType)keyValuePair.Key == project.BasicInfo.Type)
				{
					accepted = true;
				}
			}
			e.Accepted = accepted;
		}

		private void comboAllProjectType_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			RefreshProjectList();
		}

		private void gridProjectNameList_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
		{
			if (e.EditAction != DataGridEditAction.Commit)
			{
				return;
			}
			TextBox textBox = e.EditingElement as TextBox;
			Project project = e.Row.Item as Project;
			if (project != null && textBox != null)
			{
				string name = project.BasicInfo.Name;
				string text = textBox.Text;
				StringBuilder stringBuilder = new StringBuilder();
				if (string.IsNullOrEmpty(text))
				{
					stringBuilder.Append(Utility.GetMessage("msg_project_name_not_input"));
				}
				else if (name != text && ProjectManage.GetInstance().IsExistProjectName(text))
				{
					stringBuilder.Append(string.Format(Utility.GetMessage("msg_project_name_exist"), text));
				}
				if (stringBuilder.Length > 0)
				{
					MessageBox.Show(stringBuilder.ToString());
					textBox.SelectAll();
					e.Cancel = true;
				}
				else
				{
					project.Rename(text);
				}
			}
		}

		private void gridProjectNameList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (dXTabControlParamter.SelectedIndex == -1 || ((TabItem)dXTabControlParamter.Items[dXTabControlParamter.SelectedIndex]).Visibility != 0)
			{
				dXTabControlParamter.SelectedIndex = 0;
			}
			Project project = gridProjectNameList.SelectedItem as Project;
			if (project != null)
			{
				tabItemMeltParamter.Visibility = ((project.BasicInfo.Type != EProjectType.Melt && (project.BasicInfo.Type != EProjectType.IA || project.PCRProgram.Programs.Where((BaseSegment s) => s is MeltingSegment).Count() <= 0)) ? Visibility.Collapsed : Visibility.Visible);
			}
			dXTabControlParamter.RefreshTabItemStyle();
		}

		public void RefreshProjectList(bool refreshSelected = true)
		{
			view.View.Refresh();
			if (refreshSelected && gridProjectNameList.Items.Count > 0 && gridProjectNameList.SelectedItem == null)
			{
				gridProjectNameList.SelectedItem = gridProjectNameList.Items[0];
			}
		}

		private void CommandBinding_New_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void CommandBinding_New_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (this.OnProjectEdit != null)
			{
				this.OnProjectEdit(this, new ProjectRoutedEventArgs
				{
					Project = new Project()
				});
			}
		}

		private void CommandBinding_Edit_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList != null && gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_Edit_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (gridProjectNameList.SelectedItem != null && this.OnProjectEdit != null && gridProjectNameList.SelectedItem is Project)
			{
				Project project = gridProjectNameList.SelectedItem as Project;
				this.OnProjectEdit(this, new ProjectRoutedEventArgs
				{
					Project = project
				});
				ConfigSettings.GetInstance().History.AddProjectHistory(project.GetFilePath());
			}
		}

		private void CommandBinding_Import_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void CommandBinding_Import_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Title = Utility.GetMessage("Project_Memu_File_Import");
			openFileDialog.Filter = string.Format("{0}{1}|*.{2}", Project.ProjectFileExt, Utility.GetMessage("File"), Project.ProjectFileExt);
			openFileDialog.FileName = string.Empty;
			openFileDialog.FilterIndex = 1;
			openFileDialog.RestoreDirectory = true;
			openFileDialog.DefaultExt = Project.ProjectFileExt;
			openFileDialog.Multiselect = true;
			if (openFileDialog.ShowDialog() != true)
			{
				return;
			}
			bool flag = false;
			StringBuilder stringBuilder = new StringBuilder();
			string[] fileNames = openFileDialog.FileNames;
			foreach (string text in fileNames)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
				Project project = ProjectManage.GetInstance().GetProject(fileNameWithoutExtension);
				if (ProjectManage.GetInstance().IsExistProjectName(fileNameWithoutExtension))
				{
					if (project != null && project.IsEditing)
					{
						MessageBox.Show(string.Format(Utility.GetMessage("msg_project_import_deny_editing"), fileNameWithoutExtension), Utility.GetMessage("Project_Memu_File_Import"), MessageBoxButton.OK);
						continue;
					}
					if (MessageBox.Show(string.Format(Utility.GetMessage("msg_import_project_exist"), fileNameWithoutExtension), Utility.GetMessage("Project_Memu_File_Import"), MessageBoxButton.YesNo) == MessageBoxResult.No)
					{
						continue;
					}
				}
				if (project != null)
				{
					Project project2 = Project.Load(text);
					if (project2 != null)
					{
						project.Copy(project2);
						project.Save();
						flag = true;
					}
					else
					{
						stringBuilder.AppendLine(Utility.GetMessage("msg_project_import_fail"));
					}
					continue;
				}
				project = Project.Load(text);
				if (project != null)
				{
					ProjectManage.GetInstance().AddProject(project);
					project.Save();
					flag = true;
				}
				else
				{
					stringBuilder.AppendLine(Utility.GetMessage("msg_project_import_fail"));
					stringBuilder.AppendLine(text);
				}
			}
			if (flag)
			{
				RefreshProjectList();
			}
			if (stringBuilder.Length > 0)
			{
				MessageBox.Show(stringBuilder.ToString());
			}
		}

		private void CommandBinding_Export_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_Export_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			ProjectExportWindow projectExportWindow = new ProjectExportWindow();
			projectExportWindow.Owner = Utility.GetMainWindow();
			projectExportWindow.ShowDialog();
		}

		private void CommandBinding_Copy_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList != null && gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_Copy_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (gridProjectNameList.SelectedItem != null)
			{
				Project project = gridProjectNameList.SelectedItem as Project;
				if (project != null)
				{
					CopiedProject = new Project(project);
				}
			}
		}

		private void CommandBinding_Paste_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = _CopiedProject != null;
		}

		private void CommandBinding_Paste_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (CopiedProject != null)
			{
				ProjectManage.GetInstance().AddProject(ProjectManage.GetInstance().CreatePasteProject(CopiedProject));
			}
		}

		private void CommandBinding_Rename_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList != null && gridProjectNameList.SelectedItems.Count == 1;
		}

		private void CommandBinding_Rename_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (gridProjectNameList.SelectedItems.Count != 1)
			{
				return;
			}
			Project project = gridProjectNameList.SelectedItem as Project;
			ProjectReNameWindow projectReNameWindow = new ProjectReNameWindow();
			projectReNameWindow.Owner = Utility.GetMainWindow();
			projectReNameWindow.projectName.Text = project.BasicInfo.Name;
			if (projectReNameWindow.ShowDialog() == true)
			{
				string name = project.BasicInfo.Name;
				string text = projectReNameWindow.projectName.Text;
				StringBuilder stringBuilder = new StringBuilder();
				if (string.IsNullOrEmpty(text))
				{
					stringBuilder.Append(Utility.GetMessage("msg_project_name_not_input"));
				}
				else if (name != text && ProjectManage.GetInstance().IsExistProjectName(text))
				{
					stringBuilder.Append(string.Format(Utility.GetMessage("msg_project_name_exist"), text));
				}
				if (stringBuilder.Length > 0)
				{
					MessageBox.Show(stringBuilder.ToString());
				}
				else
				{
					project.Rename(text);
				}
			}
		}

		private void CommandBinding_Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList != null && gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_Delete_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			if (gridProjectNameList.SelectedItem == null)
			{
				return;
			}
			Project project = gridProjectNameList.SelectedItem as Project;
			if (project == null)
			{
				return;
			}
			if (project.IsEditing)
			{
				MessageBox.Show(Utility.GetMessage("msg_project_delete_deny_editing"), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
				return;
			}
			ProjectRoutedEventArgs projectRoutedEventArgs = new ProjectRoutedEventArgs();
			projectRoutedEventArgs.RoutedEvent = OnProjectIsUsingRoutedEvent;
			projectRoutedEventArgs.Project = project;
			projectRoutedEventArgs.IsUsing = false;
			ProjectRoutedEventArgs projectRoutedEventArgs2 = projectRoutedEventArgs;
			RaiseEvent(projectRoutedEventArgs2);
			if (projectRoutedEventArgs2.IsUsing)
			{
				MessageBox.Show(string.Format(Utility.GetMessage("msg_project_delete_deny"), projectRoutedEventArgs2.ExperimentName), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
			}
			else if (MessageBox.Show(Utility.GetMessage("msg_project_delete_confirm"), Utility.GetMessage("Delete"), MessageBoxButton.YesNo) == MessageBoxResult.Yes)
			{
				int selectedIndex = gridProjectNameList.SelectedIndex;
				ProjectManage.GetInstance().DeleteProject(project);
				selectedIndex--;
				gridProjectNameList.SelectedIndex = ((selectedIndex >= 0) ? selectedIndex : 0);
			}
		}

		private void CommandBinding_DataExport_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_DataExport_Executed(object sender, ExecutedRoutedEventArgs e)
		{
		}

		private void CommandBinding_Print_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = gridProjectNameList.SelectedItem != null;
		}

		private void CommandBinding_Print_Executed(object sender, ExecutedRoutedEventArgs e)
		{
		}

		private void CommandBinding_Help_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void CommandBinding_Help_Executed(object sender, ExecutedRoutedEventArgs e)
		{
		}

		private void ContentControl_PreviewMouseDoubleClick_1(object sender, MouseButtonEventArgs e)
		{
			CommandBinding_Edit_Executed(sender, null);
		}

		[DebuggerNonUserCode]
		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
		internal Delegate _CreateDelegate(Type delegateType, string handler)
		{
			return Delegate.CreateDelegate(delegateType, this, handler);
		}
	}
}
